﻿using AutoMapper;
using MyToDo.Api.Context.Entity;
using MyToDo.Api.Controllers.Dtos;
using MyToDo.Api.Extensions;
using System;
using System.Threading.Tasks;

namespace MyToDo.Api.Service
{
    public class LoginService : ILoginService
    {
        private readonly IUnitOfWork unitOfWork;
        private readonly IMapper mapper;

        public LoginService(IUnitOfWork unitOfWork, IMapper mapper)
        {
            this.unitOfWork = unitOfWork;
            this.mapper = mapper;
        }
        public async Task<ApiResponse> LoginAsync(UserDto dto)
        {
            try 
            {
                dto.PassWord = dto.PassWord.GetMD5();
                var repository = unitOfWork.GetRepository<User>();
                var user = await repository.GetFirstOrDefaultAsync(predicate: 
                    t => t.Account.Equals(dto.Account) && t.PassWord.Equals(dto.PassWord));
                if (user == null)
                {
                    return new ApiResponse("账号或密码错误，请重试！");
                }
                else
                {
                    return new ApiResponse(true, user);
                }
            } catch (Exception ex) {
                return new ApiResponse(ex.Message);
            }
        }

        public async Task<ApiResponse> ResgiterAsync(UserDto userDto)
        {
            try
            {
                var model = mapper.Map<User>(userDto);
                var repository = unitOfWork.GetRepository<User>();
                var userModel = await repository.GetFirstOrDefaultAsync(predicate: x => x.Account.Equals(model.Account));
                if (userModel != null)
                    return new ApiResponse($"账号:{model.Account}已存在！");
                model.CreateDate = DateTime.Now;
                model.PassWord = model.PassWord.GetMD5();
                await repository.InsertAsync(model);
                if (await unitOfWork.SaveChangesAsync() > 0)
                    return new ApiResponse(true, userDto);
                return new ApiResponse("注册失败！");
            }
            catch (Exception ex)
            {
                return new ApiResponse(ex.Message);
            }
        }
    }
}
